//HTTP Server:
import requireDirectory from 'require-directory';
import express from "express";
import http from "http";
import socket from "socket.io";
import fs from "fs";
import path from "path";
import config from "../config";

module.exports = function () {
    console.log("HTTP Server Starting...");

    let app = express();
    let server = http.Server(app);
    server.listen(config.port, function () {
        let host = server.address().address;
        let port = server.address().port;
        console.log('HTTPServer Listening at http://%s:%s', host, port);
    });
    let io = socket(server);

    //Load WebAPI Modules:
    let wrapHttp = fn => ((...args) => fn(...args).catch(e => {
        console.log("HTTP Error:", e);
        console.log(e.stack);
        args[1].json({ error: e });
    }));

    let wrapSocket = fn =>((...args) => fn(...args).catch(e => {
            console.log("Socket Error:", e);
            console.log(e.stack);
            socket.emit("failure", e.message);
    }));

    let ctx = {
        app, wrapHttp,
        io, wrapSocket,
        config,
    };

    fs.readdirSync(path.join(__dirname, "./components")).forEach((fn)=>{
        let js=fn.replace(".js","");
        console.log("api component :%s", js);
        let comp = require(path.join(__dirname, "./components",fn));
        ctx[fn]=comp(ctx);
        return comp;
    })
}